package com.byron.media.server.utils;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {

    private static Gson gson = new GsonBuilder()
            .enableComplexMapKeySerialization()
//            .serializeNulls()
            .disableHtmlEscaping().create();

    /**
     * 对象转json
     * @param obj
     * @return
     */
    public static String toJson(Object obj){
        return gson.toJson(obj);
    }


    /**
     * json 转对象
     * @param cls
     * @param json
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json, Class<T> cls){
        if(json == null || "".equals(json)){
            try {
                return cls.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        T obj = null;
        try{
            obj = gson.fromJson(json, cls);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return obj;
    }


    /**
     * json转map
     * @param json
     * @return
     */
    public static Map<String,Object> fromJson(String json) {
        if(json == null){
            return new HashMap<String,Object>();
        }
        return gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
    }


    /**
     * json字符串array转List
     * @param targetIds
     * @return
     */
    public static List<String> fromJsonStrArray(String targetIds) {
        JsonParser parser = new JsonParser();
        JsonArray targetArray = parser.parse(targetIds).getAsJsonArray();
        List<String> targetIdList = new ArrayList<String>();
        for(JsonElement element : targetArray){
            targetIdList.add(gson.fromJson(element, String.class));
        }
        return targetIdList;
    }



    public static List<Integer> fromJsonIntArray(String targetIds) {
        JsonParser parser = new JsonParser();
        JsonArray targetArray = parser.parse(targetIds).getAsJsonArray();
        List<Integer> targetIdList = new ArrayList<Integer>();
        for(JsonElement element : targetArray){
            targetIdList.add(gson.fromJson(element, Integer.class));
        }
        return targetIdList;
    }


    public static <T> T cloneObject(T object, Class<T> clazz){
        String topicJson = JsonUtils.toJson(object);
        T cloneObject = JsonUtils.fromJson(topicJson, clazz);
        return cloneObject;
    }

}
